package besta.moon.sql.expression.function;

import java.sql.*;

import besta.moon.sql.Expression;
import besta.moon.sql.parser.SQLTokenizer;
import besta.moon.MoonException;
import besta.moon.MoonCode;
import besta.moon.sql.expression.ExpressionValue;

public abstract class ExpressionFunction extends Expression {

    protected Expression param1;
    protected Expression param2;
    protected Expression param3;
    protected Expression param4;

    protected ExpressionFunction() {
        super(FUNCTION);
    }

    public abstract int getFunction();

    @Override
    public byte[] getBytes() throws Exception {
        return ExpressionValue.getBytes(getObject(), getDataType());
    }

    @Override
    public void setParams(Expression[] params) {
        super.setParams(params);
        if (params.length > 0) {
            param1 = params[0];
        }
        if (params.length > 1) {
            param2 = params[1];
        }
        if (params.length > 2) {
            param3 = params[2];
        }
        if (params.length > 3) {
            param4 = params[3];
        }
    }

    @Override
    public final void setParamAt(Expression param, int idx) {
        switch (idx) {
            case 0:
                param1 = param;
                break;
            case 1:
                param2 = param;
                break;
            case 2:
                param3 = param;
                break;
            case 3:
                param4 = param;
                break;
        }
        super.setParamAt(param, idx);
    }

    public boolean equals(Object expr) {
        if (!super.equals(expr)) {
            return false;
        }
        if (!(expr instanceof ExpressionFunction)) {
            return false;
        }
        return ((ExpressionFunction) expr).getFunction() == getFunction();
    }

    public SQLException createUnspportedDataType(int dataType) {
        Object[] params = {SQLTokenizer.getKeyWord(dataType), SQLTokenizer.getKeyWord(getFunction())};
        return MoonException.create(MoonCode.UNSUPPORTED_DATATYPE_FUNC, params);
    }

    public SQLException createUnspportedConversion(int dataType) {
        Object[] params = {SQLTokenizer.getKeyWord(dataType), SQLTokenizer.getKeyWord(getFunction())};
        return MoonException.create(MoonCode.UNSUPPORTED_CONVERSION_FUNC, params);
    }
}
